using System;
using UnityEngine;
using UnityEngine.UI;

public class HomeAdButton : MonoBehaviour
{
    public Text timesRemainText;
    public GameObject fx;
    public GameObject grayMask;
    public GameObject coinGo;
    public GameObject timeGo;
    public Button button;
    public int addCoin = 1000;
    public int AdInterval = 6 * 60 * 60;
    
    private const string AdTimeKey = "LastAdTime";
    static double lastAdTime
    {
        get
        {
            var lastTimeStr = PlayerPrefs.GetString(AdTimeKey);
            if (string.IsNullOrEmpty(lastTimeStr))
                return 0;
            return double.Parse(lastTimeStr);
        }
        set
        {
            PlayerPrefs.SetString(AdTimeKey,value.ToString());
        }
    }
    
    public double timeLeft
    {
        get
        {
            if (lastAdTime <= 0) return 0;
            
            double left = AdInterval - (UnityFunctions.GetTimeStampSeconds() - lastAdTime);
            left = Math.Max(0, left);
            return left;
        } 
    }

    private bool m_Active;


    private Animator m_Anim;
    
    void Start()
    {
        if (button == null)
            button = GetComponentInChildren<Button>();
        
        m_Anim = GetComponentInChildren<Animator>();
        
        UpdateStatus();

        coinGo.GetComponentInChildren<Text>().text = this.addCoin.ToString();
        
        if(iconPref)
            iconPref.SetActive(false);
    }

    public void OnClickAd()
    {
        AudioController.instance.PauseMusic();
        
        #if UNITY_EDITOR
        lastAdTime = UnityFunctions.GetTimeStampSeconds();
        OnAdComplete();
        #endif

        Game.Instance.adManager.PlayVideoAd( () =>
            {
                OnAdComplete();
            }
            , () =>
            {
                AudioController.instance.ResumeMusic();
            }, (err) =>
            {
                AudioController.instance.ResumeMusic();
                Game.Instance.ShowNoticePanel(Localization.instance.GetValue("ad_not_ready"));
            });
    }
    
    /// </summary>
    ZTransformAnim zTransformAnim;
    public ZTransformAnim TransformAnim
    {
        get
        {
            if (zTransformAnim == null) zTransformAnim = this.gameObject.AddComponent<ZTransformAnim>();
            return zTransformAnim;
        }
    }

    public GameObject iconPref;
    void OnAdComplete()
    {
        AudioController.instance.ResumeMusic();
        lastAdTime = UnityFunctions.GetTimeStampSeconds();
        UpdateStatus();
        
        DoActionDelay.DelayAction(1.6f,()=> MGame.instance.MUser.AddCoin(addCoin));
        
        for (int i = 0; i < 50; i++)
        {
            var mainUI = GetComponentInParent<MBattleMainUI>();
            var icon = Instantiate(iconPref, mainUI.transform);
            icon.transform.localPosition = Vector3.zero;
            icon.gameObject.SetActive(true);
            Vector3 centerPos = 1.5f * new Vector3(new RealRandom().Random(-100, 100), new RealRandom().Random(-100, 100), 0);
            TransformAnim.MoveTo(icon.transform, centerPos, .3f, () =>
            {
                DoActionDelay.DelayAction(.4f, () =>
                {
                    TransformAnim.MoveTo(icon.transform, mainUI.coinIconPos.position, .7f, () =>
                    {
                        Destroy(icon.gameObject);

                    });
                });
            }, true);
        }
    }

    void UpdateStatus()
    {
        m_Active = timeLeft <= 0;
        if(m_Active)
            Active();
        else 
            DiscActive();
    }
    
    public void Active()
    {
        coinGo.SetActive(true);
        timeGo.SetActive(false);
        if (m_Anim)
            m_Anim.enabled = true;
        if(fx)
            fx.SetActive(true);
        if(grayMask)
            grayMask.SetActive(false);
        
        if (button)
            button.interactable = true;
    }

    public void DiscActive()
    {
        coinGo.SetActive(false);
        timeGo.SetActive(true);
        if (m_Anim)
        {
            m_Anim.Play("Idle",0,0);
            m_Anim.enabled = false;
        }
        
        if(fx)
            fx.SetActive(false);
        if(grayMask)
            grayMask.SetActive(true);
        
        if (button)
            button.interactable = false;
    }

    private float m_LastPlayAnimTime;
    private void Update()
    {
        if (Time.frameCount % 30 == 0)
        {
            bool active = timeLeft <= 0;

            if (m_Active != active)
            {
                UpdateStatus();
            }

            if (m_Active)
            {
                if (Time.time - m_LastPlayAnimTime > 5)
                {
                    m_LastPlayAnimTime = Time.time;
                    if(m_Anim)
                        m_Anim.SetTrigger("Play");
                }
            }
            else
            {
                if (timesRemainText && timesRemainText.gameObject.activeInHierarchy)
                    this.timesRemainText.text = UnityFunctions.TimeToDHMS(this.timeLeft);
            }
        }
        
    }

}